package be.jhd.appserver;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import be.jhd.appserver.weblogic.DeployerCommandSender;
import be.jhd.appserver.weblogic.command.WeblogicConfig;
import be.jhd.appserver.weblogic.deployer.command.DeployCommand;
import be.jhd.appserver.weblogic.deployer.command.ListCommand;
import be.jhd.appserver.weblogic.deployer.command.UndeployCommand;
import be.jhd.downloader.utils.ConfigUtils;
import be.jhd.repository.Artifact;
import be.jhd.repository.DownloadException;
import be.jhd.repository.Downloader;
import be.jhd.repository.WarArtifact;
import be.jhd.repository.nexus.DownloaderConfig;
import be.jhd.repository.nexus.RepositoryResolver;
import be.jhd.repository.nexus.UrlBuilderImpl;
import be.jhd.utils.ArtifactNameResolver;

public class DeployArtifactTestIntegration {

	private static final Artifact artifact = new WarArtifact("be.jhd", "hello.world.web", "0.0.1", true);
	private static final WeblogicConfig config = ConfigUtils.getAsDevMainServer();
	private static final DownloaderConfig downloaderConfig = ConfigUtils.getDownloader();
	private final DeployerCommandSender sender = new DeployerCommandSender(config);

	@Test
	public void test() throws DownloadException, IOException{
		
		String response = sender.send(new ListCommand());
		
		DeployedArtifactAnalyzer analyzer = new DeployedArtifactAnalyzer(response);
		DeployedArtifact deployed = analyzer.find(artifact);
		
		if(deployed.isDeployed()){
			sender.send(new UndeployCommand(deployed));
		}
		
		UrlBuilderImpl urlBuilder = new UrlBuilderImpl(
				downloaderConfig, 
				new RepositoryResolver());
		
		Downloader downloader = new Downloader(urlBuilder);
		byte[] downloaded = downloader.download(artifact);
		
		String artifactName = ArtifactNameResolver.resolve(artifact);
		String artifactAbsolutePath = ArtifactNameResolver.resolveAbsolutePath(artifact);
		
		FileUtils.writeByteArrayToFile(new File(artifactAbsolutePath), downloaded);
		
		sender.send(new DeployCommand(artifactName, artifactAbsolutePath));
		
		FileUtils.deleteQuietly(new File(artifactAbsolutePath));
	}
	
}
